package com.gs.douban.worker;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JLabel;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;

import com.google.gson.Gson;
import com.gs.douban.model.PlayList;
import com.gs.douban.model.Song;
import com.gs.douban.utils.CookieProcesser;
import com.gs.douban.utils.HttpClientUtil;
import com.gs.douban.utils.Mp3Maker;
import com.mpatric.mp3agic.NotSupportedException;

public class LikedSongDownloader {
	private static Logger LOG = Logger.getLogger(LikedSongDownloader.class);

	public static synchronized void down(String cookie, int retry, String path,JLabel l)
			throws HttpException, IOException, InterruptedException, NotSupportedException,IllegalArgumentException {
		HttpClientUtil hc = new HttpClientUtil();
		for (int i = 1; i <= retry; i++) {
			l.setText("正在进行第"+i+"次获取,已抓取"+new File(path).list().length+"个文件");
			String r = hc
					.get("http://douban.fm/j/mine/playlist?type=n&channel=-3&from=mainsite",
							cookie);
			r = r.replaceAll("\\\\", "");
			PlayList pl = new Gson().fromJson(r, PlayList.class);
			List<Song> list = pl.getSong();
			if(list.size() == 0){
				throw new IllegalArgumentException("Cookie 错误!");
			}
			for (Song song : list) {
				Mp3Maker.make(song, path);
				l.setText("正在进行第"+i+"次获取,已抓取"+new File(path).list().length+"个文件");
			}
			LOG.info("列表歌曲下载完成");
			Thread.sleep(1000);
		}

	}
	
	public static synchronized void getList(String coo,String ck,String path) throws HttpException, IOException{
		HttpClientUtil hc = new HttpClientUtil();
		String r = null;
		String bid = "::"+CookieProcesser.process(coo).get("bid").replaceAll("\"", "");
		HashSet<Header> set = new HashSet<Header>();
		set.add(new Header("X-Requested-With", "XMLHttpRequest"));
		set.add(new Header("Referer", "http://douban.fm/mine?type=liked"));
		set.add(new Header("Cookie", coo));
		int total = 3;
		for (int i = 0; i <= total+100; i=i+15) {
			r = (hc.get("http://douban.fm/j/play_record?ck=" + ck + "&spbid="
					+ URLEncoder.encode(bid) + "&type=liked&start="+i, set));
			System.out.println(r);
			JsonFactory jfactory = new JsonFactory();
			JsonParser jParser = jfactory.createJsonParser(r);
			String result = null;
			while (jParser.nextToken() != JsonToken.END_OBJECT) {
				String fieldname = jParser.getCurrentName();
				if ("total".equals(fieldname)) {
					jParser.nextToken();
					total = (jParser.getIntValue());
				} else if ("songs".equals(fieldname)) {
					jParser.nextToken();
					while (jParser.nextToken() != JsonToken.END_ARRAY) {
						String title = null;
						String artist = null;
						while (jParser.nextToken() != JsonToken.END_OBJECT) {
							String songfieldname = jParser.getCurrentName();
							if ("artist".equals(songfieldname)) {
								jParser.nextToken();
								artist = (jParser.getText());
							} else if ("title".equals(songfieldname)) {
								jParser.nextToken();
								title = (jParser.getText());
							}
							if (title!=null&&artist!=null) {
								result += title + "-" + artist + "\n\r";
								title = null;
								artist = null;
							}
						}
					}
					FileUtils.writeStringToFile(new File(path.endsWith("/")?path:(path+"/")+"list.txt"), result, true);
				}
			}
			jParser.close();
		}
	} 
}
